<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Membership
 * @version 	1.0
 * @author 		Rukan <rukanhitokiri@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
class Zhelpdeskmodule extends Module
{	
	/**
	 * Install & uninstall SQL
	 * 
	 * $param string $file
	 * @return boolean
	 */
  	protected function _sql($file)
  	{
  		if ((!file_exists(dirname(__FILE__).'/../../'.$file)) 
		   || (!$sql = file_get_contents(dirname(__FILE__).'/../../'.$file)))
				return false;
		$sql = str_replace(array('PREFIX_', 'ENGINE_TYPE'), array(_DB_PREFIX_, _MYSQL_ENGINE_), $sql);
		$sql = preg_split("/;\s*[\r\n]+/", $sql);
		
		foreach ($sql AS $query)
			if (!Db::getInstance()->Execute(trim($query)))
				return false;
		return true;
	}
	
	/**
	 * Add new tab in administration
	 * 	 
	 * $param array $data
	 * @return boolean
	 */
  	protected function _addAdminTab($data = array())
  	{
  		if (isset($data['parentClassName']) AND $data['parentClassName']!='')
			$idTabParent = Tab::getIdFromClassName($data['parentClassName']);
		else {
			$idTabParent = 0;
		}
		
    	$languages = Language::getlanguages(false);	/*All languages id*/
     	foreach ($languages as $langs) {
        	$tabNames[$langs['id_lang']] = $data['childTabName'];
    	}
    	$tab = new Tab();
    	
		$tab->module = $this->name;
    	$tab->name = $tabNames;
    	$tab->class_name = $data['childClassName'];
    	$tab->id_parent = $idTabParent;
    	
    	if (!$tab->save())
      		return false;
     	if ($idTabParent==0) {
     		Db::getInstance()->Executes ('INSERT INTO `'._DB_PREFIX_.'tab` (`id_parent`, `position`) VALUES ('.$tab->id.', \'0\')');
     	}
    	return true;
	}
	
	/**
	 * Remove tab in administration
	 * 
	 * @param string $className
	 * @return boolean
	 */
	protected function _removeAdminTab($className)
	{
		$idTab = Tab::getIdFromClassName($className);
		$tab = new Tab($idTab);
		if (!$tab->delete())
      		return false;
		return true;
	}
	
	/**
	 * display Form Configuration
	 * 
	 * @return string html
	 */
 	protected function _displayForm()
 	{
 		$this->_displayFormConfig();
 		$this->_displayExtraFormConfig();
 		$this->_displaySupport();
 		return $this->_html;
	}
	
	/**
	 * display Extra Form Config (All tab)
	 * 
     * @return string html
	 */
	protected function _displayExtraFormConfig()
	{
		
	}
	
	/**
	 * display Support
	 * 
     * @return string html
	 */
	protected function _displaySupport()
	{
		$this->_html .= '
 		<fieldset><legend><img src="'.$this->_path.'logo.gif" /> '.$this->l('Support').'</legend>
			<img src="'.$this->_path.'img/logo.jpg" style="float:right;margin-left:10px" />
			<br />
			'.$this->l('The full installation guide is available on').' <a href="http://zprofess.com" target="_blank" style="text-decoration:underline">'.$this->l('the official Zprofess website').'</a>.
			<br /><br />
			'.$this->l('Find more information at').' <a href="http://zprofess.com" target="_blank" style="text-decoration:underline">'.$this->l('http://zprofess.com').'</a>.
		</fieldset>
		<div class="clear"></div>';
	}
	
	/**
	 * display Form Config (All tab)
	 * 
     * @return string html
	 */
	protected function _displayFormConfig()
	{
		
	}
	/**
	 * 
	 * Load TinyMce editor
	 * 
	 * @return string html
	 */
	public function loadTinyMCE()
	{
		global $cookie;
		$defaultLanguage = (int)(Configuration::get('PS_LANG_DEFAULT'));
		$languages = Language::getLanguages(false);
		$iso = Language::getIsoById((int)$cookie->id_lang);
		$content = '';
		if (version_compare(_PS_VERSION_, '1.4.0.0') >= 0)
			$content .= '
			<script type="text/javascript">	
				var iso = \''.(file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en').'\' ;
				var pathCSS = \''._THEME_CSS_DIR_.'\' ;
				var ad = \''.dirname($_SERVER['PHP_SELF']).'\' ;
			</script>
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tiny_mce/tiny_mce.js"></script>
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce.inc.js"></script>
			<script language="javascript">id_language = Number('.$defaultLanguage.');</script>';
		else
		{
			$content .= '
			<script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
			<script type="text/javascript">
				tinyMCE.init({
					mode : "textareas",
					theme : "advanced",
					plugins : "safari,pagebreak,style,layer,table,advimage,advlink,inlinepopups,media,searchreplace,contextmenu,paste,directionality,fullscreen",
					theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
					theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,,|,forecolor,backcolor",
					theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,media,|,ltr,rtl,|,fullscreen",
					theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,pagebreak",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_statusbar_location : "bottom",
					theme_advanced_resizing : false,
					content_css : "'.__PS_BASE_URI__.'themes/'._THEME_NAME_.'/css/global.css",
					document_base_url : "'.__PS_BASE_URI__.'",
					width: "600",
					height: "auto",
					font_size_style_values : "8pt, 10pt, 12pt, 14pt, 18pt, 24pt, 36pt",
					template_external_list_url : "lists/template_list.js",
					external_link_list_url : "lists/link_list.js",
					external_image_list_url : "lists/image_list.js",
					media_external_list_url : "lists/media_list.js",
					elements : "nourlconvert",
					entity_encoding: "raw",
					convert_urls : false,
					language : "'.(file_exists(_PS_ROOT_DIR_.'/js/tinymce/jscripts/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en').'"
				});
				id_language = Number('.$defaultLanguage.');
			</script>';
		}
		return $content;
	}
	
	/**
	 * 
	 * load labrary jquery color picker
	 * 
	 * @return string html
	 */
	public static function loadJsColorPicker()
	{
		return '<script type="text/javascript" src="'._PS_JS_DIR_.'/jquery/jquery-colorpicker.js"></script>';
	}

	/**
	 * add element for form
	 *
	 * @param string $type type element html render
	 * @param array	$fields
     * @return string html
	 */
	public function addElement($type, $fields = array(),$lang = false)
	{	
		if ($type == 'text')
			return $this->renderTextInput($fields, $lang);
		elseif ($type == 'color')
			return $this->renderColorPicker($fields);
		elseif ($type == 'select')
			return $this->renderSelect($fields);
		elseif ($type == 'yesno')
			return $this->renderYesNoOption($fields);
		elseif ($type == 'button')
			return $this->renderButton($fields);
		elseif ($type == 'textarea')
			return $this->renderTextarea($fields, $lang);
		elseif ($type == 'checkbox')
			return $this->renderCheckbox($fields);
			
	}
	
	/**
	 * display Color Picker
	 *
	 * @param array	$fields
     * @return string html
	 */
	public function renderColorPicker($fields = array())
	{
		// <script type="text/javascript" src="'._PS_JS_DIR_.'/jquery/jquery-colorpicker.js"></script>
		return '
		<label>'.$this->l($fields['label']).'</label>
		<div class="margin-form">
			<input type="color" width="50px" data-hex="true" class="color mColorPickerInput" name="'.$fields['name'].'" value="'.htmlentities(Configuration::get($fields['value']), ENT_COMPAT, 'UTF-8').'" />
		</div>
		<div class="clear"></div>';
	}
	
	/**
	 * display TextInput
	 *
	 * @param array	$fields
	 * @param bool $lang
     * @return string html
	 */
	public function renderTextInput($fields = array(), $lang = false)
	{
		if (!$lang) {
			$_html = '	
			<label>'.$this->l($fields['label']).'</label>
			<div class="margin-form">
				<input '.(array_key_exists ('style',$fields)==true?'style="'.$fields['style'].'"':'').' name="'.$fields['name'].'" id="'.$fields['name'].'" '.(array_key_exists ('type',$fields)==true?'type="'.$this->l($fields['type']).'"':'type="text"').' class="text" value="'.Configuration::get($fields['value']).'"/> '.(array_key_exists ('expand',$fields)==true?$this->l($fields['expand']):'').'
				<p class="clear">'.$this->l($fields['note']).'</p>
			</div>
			<div class="clear"></div>';
		}
		else {
			$values = Configuration::getInt($fields['value']); 
			$_html = '<label>'.$this->l($fields['label']).'</label>
				<div class="margin-form">';
				foreach (Language::getLanguages(false) AS $language)
					$_html .= '
					<div id="'.$fields['name'].'_'.$language['id_lang'].'" style="float: left;'.($language['id_lang'] != (int)(Configuration::get('PS_LANG_DEFAULT')) ? 'display:none;' : '').'">
						<input type="text" name="'.$fields['name'].'_'.$language['id_lang'].'" id="'.$fields['name'].'_'.$language['id_lang'].'" value="'.(isset($values[$language['id_lang']]) ? $values[$language['id_lang']] : '').'" />
					</div>';
				$_html .= $this->displayFlags(Language::getLanguages (false), (int)(Configuration::get('PS_LANG_DEFAULT')), $fields['langtags'], $fields['name']);
				$_html .= '</div><div class="clear"></div>';
		
		}
		return $_html;
	}
	
		
	/**
	 * display Select option
	 * 
	 * @param array	$fields
     * @return string html
	 */
	public function renderSelect($fields = array())
	{
		$html = '	
				<label>'.$this->l($fields['label']).'</label>
				<div class="margin-form">
					<select name="'.$fields['name'].'" id="'.$fields['name'].'" '.(array_key_exists ('style',$fields)==true?'style="'.$this->l($fields['style']).'"':'').'>';
			foreach($fields['values'] as $value){
				if (array_key_exists ('value',$value))
					$html .= '	<option value="'.$value['value'].'" '.(Configuration::get($fields['value']) == $value['value'] ? "selected='selected'" : '').'>'.$value['name'].'</option>';
				else 
					$html .= '	<option value="'.$value['name'].'" '.(Configuration::get($fields['name']) == $value['name'] ? "selected='selected'" : '').'>'.$value['name'].'</option>';
			}
		
		$html .= '	</select> '.(array_key_exists ('expand',$fields)==true?$this->l($fields['expand']):'').'
					<p class="clear">'.(array_key_exists('note',$fields)==true ? $this->l($fields['note']) : '').'</p>
				</div>
				<div class="clear"></div>';
		return $html;
	}
	
	/**
	 * display YesNo option radio option
	 * 
	 * @param array	$fields
     * @return string html
	 */
	public function renderYesNoOption($fields = array())
	{
		return '	
		<label>'.$this->l($fields['label']).'</label>
		<div class="margin-form">
			<input type="radio" name="'.$fields['name'].'" id="'.$fields['name'].'_on" value="1" '.($fields['value'] ? 'checked="checked" ' : '').'/>
			<label class="t" for="'.$fields['name'].'_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
			<input type="radio" name="'.$fields['name'].'" id="'.$fields['name'].'_off" value="0" '.(!$fields['value'] ? 'checked="checked" ' : '').'/>
			<label class="t" for="'.$fields['name'].'_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
			<p class="clear">'.$this->l($fields['note']).'</p>
		</div>
		<div class="clear"></div>';
	}
	
/**
	 * display button Save
	 * 
	 * @param array	$fields
     * @return string html
	 */
	public function renderButton ($fields = array()) {
		
		$html = '
			<center>
				<input style="width:100px !important;" type="submit" name="'.$fields['name'].'" value="'.$this->l($fields['value']).'" class="button" /> '.(array_key_exists ('expand',$fields)==true?$this->l($fields['expand']):'').'
			</center>
		';
		return $html;
	}
	
	/**
	 * display Textarea
	 * @param array	$fields
	 * @param bool $lang 
     * @return string html
	 */
	public function renderTextarea ($fields = array(),$lang = false) {
		if (!$lang) {
			$html ='
			<label>'.$this->l($fields['label']).'</label>
			<div class="margin-form">
				<textarea class="'.(array_key_exists ('class',$fields)==true ? $this->l($fields['class']):'').'" cols="70" rows="30" name="'.$fields['name'].'">'.Configuration::get($fields['value']).'</textarea>  '.(array_key_exists ('expand',$fields)==true?$this->l($fields['expand']):'').'
				<p class="clear">'.$this->l($fields['note']).'</p>
			</div>
			<div class="clear"></div>';
		}
		else {
			$html = '<label>'.$this->l($fields['label']).'</label>
				<div class="margin-form">';
				foreach (Language::getLanguages (false) as $language)
					$html .= '
					<div id="'.$fields['name'].'_'.$language['id_lang'].'" style="float: left;'.($language['id_lang'] != (int)(Configuration::get('PS_LANG_DEFAULT')) ? 'display:none;' : '').'">
						<textarea class="'.(array_key_exists ('class',$fields)==true ? $this->l($fields['class']):'').'" cols="70" rows="30" id="id_'.$fields['name'].'_'.$language['id_lang'].'" name="'.$fields['name'].'_'.$language['id_lang'].'">'.htmlentities(stripslashes(Configuration::get($fields['value'],$language['id_lang'])), ENT_COMPAT, 'UTF-8').'</textarea>
					</div>';
				$html .= $this->displayFlags(Language::getLanguages (false), (int)(Configuration::get('PS_LANG_DEFAULT')), $fields['langtags'], $fields['name']);
				$html .= '</div><div class="clear"></div><br><br>';
		}
		return $html;
	}
	/**
	 * display Checkbox
	 * @param array	$fields
     * @return string html
	 */
	
	public function renderCheckbox ($fields = array()) {
		$html ='
		<label>'.$this->l($fields['label']).'</label>
		<br>
		<br>
		<div style="padding-left:127px">
		<table cellspacing="0" cellpadding="0" style="width: 18em;" class="table">
		<tbody><tr>
			<th><input type="checkbox" onclick="checkDelBoxes(this.form, \''.$this->l($fields['name']).'[]\', this.checked)" class="noborder" name="checkme"></th>
			<th>Name Day</th>
			<th colspan="20">Time </th>
		</tr>
		';
			foreach ($fields['field'] as $item) {
				$time = Configuration::get('WORKING_TIME_'.$item);
				$time = $this->getTimeWorking ($time);
				$html .= '<tr>
							<td><input type="checkbox" name="'.$this->l($fields['name']).'[]" value="'.$this->l($item).'" '.(in_array($item, $fields['value'])?'checked="checked"':'').' /></td>
							<td><label class="t" for="groupBox_1">'.$this->l($item).'</label></td>';
							$html .= '	<td> <select name="'.$this->l($item).'_h" > ';
				for ($i=0;$i<=12;$i++)
							$html .= '
								  <option '.($time['h']==$i?'selected="selected"':'').'>'.(strlen((String)$i)==1?'0'.$i:$i).'</option>';		
				$html .='				  
								</select></td>';
				
				$html .= '	<td><select name="'.$this->l($item).'_m">';
				for ($i=0;$i<60;$i++)
							$html .= '
								  <option '.($time['m']==$i?'selected="selected"':'').'>'.(strlen((String)$i)==1?'0'.$i:$i).'</option>';		
				$html .='				  
								</select></td>';
				$html .= '	<td><select name="'.$this->l($item).'_b">';
							$html .= '
								  <option  '.($time['b']=='AM'?'selected="selected"':'').'>AM</option>
								  <option '.($time['b']=='PM'?'selected="selected"':'').'>PM</option>';		
				$html .='				  
								</select></td>';
				$html .= '	<td>';
							$html .= '
								  To';		
				$html .='				  
								</td>';
				$html .= '	<td> <select name="'.$this->l($item).'_th">';
				for ($i=0;$i<=12;$i++)
							$html .= '
								  <option '.($time['th']==$i?'selected="selected"':'').'>'.(strlen((String)$i)==1?'0'.$i:$i).'</option>';		
				$html .='				  
								</select></td>';
				
				$html .= '	<td><select name="'.$this->l($item).'_tm">';
				for ($i=0;$i<60;$i++)
							$html .= '
								  <option '.($time['tm']==$i?'selected="selected"':'').'>'.(strlen((String)$i)==1?'0'.$i:$i).'</option>';		
				$html .='				  
								</select></td>';
				$html .= '	<td><select name="'.$this->l($item).'_tb">';
							$html .= '
								  <option  '.($time['tb']=='AM'?'selected="selected"':'').'>AM</option>
								  <option '.($time['tb']=='PM'?'selected="selected"':'').'>PM</option>';		
				$html .='				  
								</select></td>';
				$html .= '	<td>AND</td>';
				$html .= '<td > <select name="'.$this->l($item).'_hand" > ';
				for ($i=0;$i<=12;$i++)
							$html .= '
								  <option '.($time['hand']==$i?'selected="selected"':'').'>'.(strlen((String)$i)==1?'0'.$i:$i).'</option>';		
				$html .='				  
								</select>
						  </td>';
				
				$html .= '	<td ><select name="'.$this->l($item).'_mand">';
				for ($i=0;$i<60;$i++)
							$html .= '
								  <option '.($time['mand']==$i?'selected="selected"':'').'>'.(strlen((String)$i)==1?'0'.$i:$i).'</option>';		
				$html .='				  
								</select></td>';
				$html .= '	<td ><select name="'.$this->l($item).'_band">';
							$html .= '
								  <option  '.($time['band']=='AM'?'selected="selected"':'').'>AM</option>
								  <option '.($time['band']=='PM'?'selected="selected"':'').'>PM</option>';		
				$html .='				  
								</select></td>';
				$html .= '	<td class="zhelpdesk_td_and">';
							$html .= '
								  To';		
				$html .='				  
								</td>';
				$html .= '	<td > <select name="'.$this->l($item).'_thand">';
				for ($i=0;$i<=12;$i++)
							$html .= '
								  <option '.($time['thand']==$i?'selected="selected"':'').'>'.(strlen((String)$i)==1?'0'.$i:$i).'</option>';		
				$html .='				  
								</select></td>';
				
				$html .= '	<td ><select name="'.$this->l($item).'_tmand">';
				for ($i=0;$i<60;$i++)
							$html .= '
								  <option '.($time['tmand']==$i?'selected="selected"':'').'>'.(strlen((String)$i)==1?'0'.$i:$i).'</option>';		
				$html .='				  
								</select></td>';
				$html .= '	<td><select name="'.$this->l($item).'_tband">';
							$html .= '
								  <option  '.($time['tband']=='AM'?'selected="selected"':'').'>AM</option>
								  <option '.($time['tband']=='PM'?'selected="selected"':'').'>PM</option>';		
				$html .='				  
								</select></td>';
				$html .='
						 </tr>';
			}
		
		$html .= '</tbody></table>
		<p class="clear">'.$this->l($fields['note']).'</p>
		</div>
		<div class="clear"></div>';
		return $html;
	}
	
	public function getTimeWorking ($time) {
		$rs1 = explode (';',$time);
		$time = $rs1[0]; 
		$rs = explode ('-',$time);
		$rs[0] = explode (' ',$rs[0]);
		$rs[0][0] = explode (':',$rs[0][0]);
		$rs[1] = explode (' ',$rs[1]);
		$rs[1][0] = explode (':',$rs[1][0]);
		$kq['h'] = $rs[0][0][0];
		$kq['m'] = $rs[0][0][1];
		$kq['b'] = $rs[0][1];
		$kq['th'] = $rs[1][0][0];
		$kq['tm'] = $rs[1][0][1];
		$kq['tb'] = $rs[1][1];
		
		$time = $rs1[1]; 
		$rs = explode ('-',$time);
		$rs[0] = explode (' ',$rs[0]);
		$rs[0][0] = explode (':',$rs[0][0]);
		$rs[1] = explode (' ',$rs[1]);
		$rs[1][0] = explode (':',$rs[1][0]);
		$kq['hand'] = $rs[0][0][0];
		$kq['mand'] = $rs[0][0][1];
		$kq['band'] = $rs[0][1];
		$kq['thand'] = $rs[1][0][0];
		$kq['tmand'] = $rs[1][0][1];
		$kq['tband'] = $rs[1][1];
		return $kq;
	}
	
	/**
	  * Display flags in forms for translations
	  *
	  * @param array $languages All languages available
	  * @param integer $default_language Default language id
	  * @param string $ids Multilingual div ids in form
	  * @param string $id Current div id]
	  * @param boolean $return define the return way : false for a display, true for a return
	  * @param boolean $use_vars_instead_of_ids use an js vars instead of ids seperate by "Â¤"
	  */
	public function displayFlags($languages, $default_language, $ids, $id, $return = true, $use_vars_instead_of_ids = false)
	{
		if (sizeof($languages) == 1)
			return false;
		$output = '
		<div class="displayed_flag">
			<img src="../img/l/'.$default_language.'.jpg" class="pointer" id="language_current_'.$id.'" onclick="toggleLanguageFlags(this);" alt="" />
		</div>
		<div id="languages_'.$id.'" class="language_flags">
			'.$this->l('Choose language:').'<br /><br />';
		foreach ($languages as $language)
			if($use_vars_instead_of_ids)
				$output .= '<img src="../img/l/'.(int)($language['id_lang']).'.jpg" class="pointer" alt="'.$language['name'].'" title="'.$language['name'].'" onclick="changeLanguage(\''.$id.'\', '.$ids.', '.$language['id_lang'].', \''.$language['iso_code'].'\');" /> ';
			else
				$output .= '<img src="../img/l/'.(int)($language['id_lang']).'.jpg" class="pointer" alt="'.$language['name'].'" title="'.$language['name'].'" onclick="changeLanguage(\''.$id.'\', \''.$ids.'\', '.$language['id_lang'].', \''.$language['iso_code'].'\');" /> ';
		$output .= '</div>';

		if ($return)
			return $output;
		echo $output;
	}
}